package org.alino.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

/**
 * @Desc TODO
 * @Author by Brant
 * @Date 2016/11/18
 */
public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static final int FILE_BUFFER_SIZE = 400 * 1024; // 400K

    public static String getRootPath(){
        return System.getProperty("alino.root");
    }

    public static String getCurrentFolderPath(){
        return new File("").getAbsolutePath();
    }

    public static String removePrefix(String src, String prefix) {
        if (src != null && src.startsWith(prefix)) {
            return src.substring(prefix.length());
        }
        return src;
    }


    public static String removeRootPath(String src){
        return removePrefix(src, getRootPath());
    }

    public static void copyFile(File src, File dst) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src), FILE_BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst), FILE_BUFFER_SIZE);
            byte[] buffer = new byte[FILE_BUFFER_SIZE];
            while (in.read(buffer) > 0) {
                out.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void copyFile(MultipartFile src, File desc) {
        FileOutputStream out = null;
        try {
            byte[] bytes = src.getBytes();
            if(!desc.getParentFile().exists()){

                desc.getParentFile().mkdirs();
            }
            out = new FileOutputStream(desc, false);
            out.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void delFile(String path){
        File file = new File(path);
        if(file.exists() && file.isFile()){
            file.delete();
        }
    }

    public static float getFileKB(long byteFile){
        if(byteFile==0)
            return 0f;
        long kb=1024;
        return (float)byteFile/kb;
    }

    public static float getFileMB(long byteFile){
        if(byteFile==0)
            return 0f;
        long mb=1024*1024;
        return (float)byteFile/mb;
    }

    public static String getFileName(String fileName) {
        if (fileName == null || fileName.equals("")) {
            return "";
        } else {
            return fileName.substring(0, fileName.lastIndexOf("."));
        }
    }

    public static String getExtention(String fileName) {
        if (fileName == null || fileName.equals("")) {
            return "";
        } else {
            return fileName.substring(fileName.lastIndexOf("."));
        }
    }

    public static void SaveFile(InputStream stream, String basePath, String filePath) throws IOException {
        File file = new File(basePath + filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fs = new FileOutputStream(basePath + filePath);
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }
    public static void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream fs = new FileOutputStream(path + File.separator + filename);
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
    }
    public static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (Exception e) {
            logger.error("下载文件失败："+ e.getMessage());
        }
        return buffer;
    }

    // 转换文件大小
    public static String FormatFileSize(long fileS) {

        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    public static String getData(InputStream in) {
        String result = "";
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = "";
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (result != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 写文件
     *
     * @param path
     *            文件的路径
     * @param content
     *            写入文件的内容
     */
    public static void writerText(String path, String content, String fileName, boolean append) {

        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            OutputStreamWriter write = new OutputStreamWriter(
                    new FileOutputStream(path +  File.separator + fileName, append), "utf-8");
            BufferedWriter bw1 = new BufferedWriter(write);
            bw1.write(content);
            bw1.flush();
            bw1.close();
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

    public static void downloadLocal(String path, String saveFileName, HttpServletResponse response) throws FileNotFoundException {
        // 读到流中
        InputStream inStream = new FileInputStream(path);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + saveFileName + "\"");

        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len;
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            while ((len = inStream.read(b)) > 0){
                outputStream.write(b, 0, len);
                outputStream.flush();
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void downloadNet(HttpServletResponse response) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        URL url = new URL("windine.blogdriver.com/logo.gif");
        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("c:/abc.gif");
            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
